public class Solution02 {
	public int[][] generateMatrix(int n) {
		int[][] arr = new int[n][n];
		// 定义上下左右的边界
		int left = 0;
		int right = n - 1;
		int top = 0;
		int bottom = n - 1;

		int endNum = n * n;
		int value = 1;
		// 采用左闭右开的规则填充
		while (value < endNum) { // value <= endNum会导致n为奇数时无限循环
			int row; // 行
			int culumn; // 列
			// 上侧
			for (culumn = left; culumn < right; culumn++) {
				arr[top][culumn] = value++;
			}
			// 右侧
			for (row = top; row < bottom; row++) {
				arr[row][right] = value++;
			}
			// 下侧
			for (culumn = right; culumn > left; culumn--) {
				arr[bottom][culumn] = value++;
			}
			// 左侧
			for (row = bottom; row > top; row--) {
				arr[row][left] = value++;
			}
			// System.out.println("value = " + value);
			top++;
			right--;
			bottom--;
			left++;
			// System.out.println("left=" + left);
			// System.out.println("ritght=" + right);
			// System.out.println("top=" + top);
			// System.out.println("bottom=" + bottom);
		}
		if (n % 2 == 1) {
			arr[n / 2][n / 2] = value;
		}
		return arr;
	}
}
